
package com.funo.government.info.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.funo.government.info.R;
import com.funo.government.info.view.MainActivity;

@SuppressLint("NewApi")
public class DownFile extends IntentService {

    public DownFile() {
        super("liancheng_download");
    }

    private static String TAG = "DownFile";

    private static final int id = 10243333;

    // 更新通知栏的时间间隔
    private static final int INTERVAL_UPDATE = 1000;

    // 通知栏
    private NotificationManager downloadNM;

    private Notification downloadNotification = null;

    private File file;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // @Override
    // public int onStartCommand(Intent intent, int flags, int startId) {
    // if (intent != null) {
    // downLoadUrl = intent.getStringExtra("url");
    // }
    // LogUtils.i(TAG, "downLoadUrl is " + downLoadUrl);
    // UpdateAsyncTask task = new UpdateAsyncTask();
    // if (!TextUtils.isEmpty(downLoadUrl)) {
    // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
    // task.execute(downLoadUrl);
    // } else {
    // task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, downLoadUrl);
    // }
    // }
    // return super.onStartCommand(intent, flags, startId);
    // }

    /**
     * 初始化通知栏
     */
    public void showNF() {
        /**
         * 添加顶部下载通知
         */
        downloadNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        downloadNotification = new Notification();
        downloadNotification.icon = R.drawable.ic_launcher;
        downloadNotification.tickerText = getString(R.string.app_name);
        downloadNotification.when = System.currentTimeMillis();
        // downloadNotification = new Notification(R.drawable.logo,
        // this.getString(R.string.app_name),
        // System.currentTimeMillis());
        downloadNotification.contentView = new RemoteViews(this.getPackageName(), R.layout.nf);
        // 设置进度条的最大进度和初始进度
        downloadNotification.contentView.setProgressBar(R.id.nf_probar, 100, 0, false);
        // 显示下载的包名
        downloadNotification.contentView.setTextViewText(R.id.nf_name,
                this.getString(R.string.app_name));

        // 显示下载的进度
        downloadNotification.contentView.setTextViewText(R.id.nf_tv_probar, "0%");

        // 增加声音提示
        // downloadNotification.defaults=Notification.DEFAULT_SOUND;
        // clear能够取消
        downloadNotification.flags = Notification.FLAG_AUTO_CANCEL;
        // 不能被clear
        // downloadNotification.flags = Notification.FLAG_ONGOING_EVENT;
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        downloadNotification.contentIntent = contentIntent;
        // 显示通知
        downloadNM.notify(id, downloadNotification);
        // 更新进度条
        // upDateProgressBar();

    }

    // private class UpdateAsyncTask extends AsyncTask<String, Integer, Boolean>
    // {
    // @Override
    // protected void onPreExecute() {
    // super.onPreExecute();
    // showNF();
    // }
    //
    // @Override
    // protected Boolean doInBackground(String... params) {
    // return true;
    //
    // }
    //
    // @Override
    // protected void onProgressUpdate(Integer... values) {
    // Integer process = values[0];
    // // 更新通知栏进度
    // updateProcess(process);
    // }
    //
    // @Override
    // protected void onPostExecute(Boolean result) {
    // if (isCancelled() || !result) {
    // downloadNM.cancel(id);
    // stopSelf();
    // return;
    // }
    // installApk();
    // // 取消通知栏
    // downloadNM.cancel(id);
    // // 关闭服务
    // stopSelf();
    // super.onPostExecute(result);
    // }
    //
    // }
    /**
     * 更新通知栏进度
     * 
     * @param process 进度
     */
    private void updateProcess(Integer process) {
        if (downloadNotification != null) {
            downloadNotification.contentView.setProgressBar(R.id.nf_probar, 100, process, false);
            downloadNotification.contentView.setTextViewText(R.id.nf_tv_probar, process + "%");
            downloadNM.notify(id, downloadNotification);
        }
    }

    /**
     * 安装apk
     */
    private void installApk() {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(i);
    }

    /**
     * 下载apk
     * 
     * @param urlString apk地址
     * @return
     */
    private Boolean downloadApk(String urlString) {
        try {
            file = new File(Environment.getExternalStorageDirectory() + "/" + "longyan.apk");
            file.createNewFile();
            // Log.i(TAG, "创建成功");
            // Log.i(TAG, "getPath is " + file.getPath());
            URL u = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(5000);
            // 得到下载的总长度
            int contentlength = conn.getContentLength();
            // System.out.println("总长度" + contentlength);
            // 得到输入流
            InputStream is = conn.getInputStream();
            FileOutputStream out = new FileOutputStream(file);
            int current = 0;
            int x = 0;
            byte[] arr = new byte[1024];
            long last = System.currentTimeMillis();
            long now = 0l;
            while ((current = is.read(arr)) != -1) {
                if (!NetUtils.isConnected(DownFile.this)) {
                }
                out.write(arr, 0, current);
                x = x + current;
                now = System.currentTimeMillis();
                if (now - last > INTERVAL_UPDATE) {
                    int progress = (x * 100) / contentlength;
                    updateProcess(progress);
                    // publishProgress((x * 100) / contentlength);
                    last = now;
                }
            }
            out.flush();
            is.close();
            out.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        showNF();
        String downLoadUrl = intent.getStringExtra("url");
        LogUtils.d(TAG, "download start. url=" + downLoadUrl);
        if (downloadApk(downLoadUrl)) {
            installApk();
        }
        downloadNM.cancel(id);
    }
}
